package service

import (
	"context"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"inventory/internal/constant"

	"inventory/internal/model"
)

// CheckUsagePermission
func (s *Service) CheckUsagePermission(ctx context.Context, empId, pStoreId, warehouseId uint32, route string) (
	warehouse *model.Warehouse, err error) {
	if warehouse, err = s.dao.GetWarehouseInfoInternal(ctx, warehouseId); err != nil {
		if errors.Cause(err) == gorm.ErrRecordNotFound {
			err = constant.ErrWarehouseNotExist
		}
		return
	}
	if warehouse.Status != constant.WarehouseEnable {
		err = constant.ErrWarehouseNotExist
		return
	}
	if pStoreId != 0 && pStoreId != warehouse.StoreID {
		err = constant.ErrPermissionError
		return
	}
	if err = s.downstream.CheckInventoryPermission(ctx, empId, warehouseId); err != nil {
		return
	}
	return
}
